package com.demo.datastructure.stack;

/**
 * @description:
 * @author: ljr
 * @time: 2021/4/27 11:27
 */
public class MinStack {
    private Integer[] args = new Integer[10];

    private int count;

    private int min;

    private int length = 10;

    /** initialize your data structure here. */
    public MinStack() {
    }

    public void push(int val) {
        if(count == 0){
            min = val;
        }else{
            if(val < min){
                min = val;
            }
        }

        if(count+1 > length){
            grow();
        }
        ++count;
        args[length-count]=val;
    }

    public void pop() {
        int val = args[length-count];
        args[length-count--] = null;
        if(count == 0){
            min = 0;
            return;
        }

        if(val == min){
            min = args[length-1];
            for(int i = 2; i <= count; i++){
                if(args[length-i] < min){
                    min = args[length-i];
                }
            }
        }

    }

    public int top() {
        return args[length-count];
    }

    public int getMin() {
        return min;
    }

    private boolean grow(){
        int newlength = length*2;
        Integer[] newArgs =  new Integer[newlength];
        for(int i = 0; i < length; i++){
            newArgs[i+length] = args[i];
        }
        args = newArgs;
        length = newlength;
        return true;
    }
}
